const assert = require('assert');

module.exports = class extends think.Controller {
  constructor(ctx) {
    super(ctx);
    assert(think.isFunction(this.model), 'this.model must be a function');
  }

  async __before(action) {

  }

  // POST:
  // {
  //   "username":"root",
  //   "password":"123456"
  //   }

  // token 生成
  // {
  //   "errno": 0,
  //   "errmsg": "",
  //   "data": {
  //     "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJpZCI6MSwidXNlcm5hbWUiOiJyb290IiwiZW1haWwiOm51bGwsInFxIjoiIiwiZ2l0aHViIjpudWxsLCJ6aGlodSI6bnVsbCwid2VpYm8iOm51bGwsInBhc3N3b3JkIjoiMjRkOGNlZTllZDc5M2I5ZjgxOGI2YzRiNjdhYWU5YWEiLCJlbmNyeXB0IjoiTWplNXNvd1Q3In0sImlhdCI6MTUyOTkwMzcwOSwiZXhwIjoxNTI5OTA3MzA5fQ.VsWQKaFqkXmjbPTflsnXLfB5w7W1ZJGFNfDwNQ97QxU"
  //   }
  // }
  async postAction() {
    await this.session('userInfo', null);

    const ip = this.ctx.ip;

    const username = this.post('username');
    const password = this.post('password');
    const user = this.model('user');
    const userInfo = await user.where({ username: username }).find();
    if (think.isEmpty(userInfo)) {
      return this.fail('用户不存在');
    }
    const result = user.verifyPassword(userInfo, password);
    if (think.isEmpty(result)) {
      user.where({ username: username }).increment('login_fail_count');
      return this.fail('密码不正确');
    }

    const lastLoginTime = Math.round(new Date().getTime() / 1000);
    user.where({ username: username }).update({ last_login_ip: ip, last_login_time: lastLoginTime, login_count: userInfo.login_count + 1 });
    userInfo.last_login_time = lastLoginTime;
    const token = await this.session('userInfo', userInfo);
    return this.success({ token: token });
  }
};
